package com.fr.data;

import com.fr.base.Parameter;
import com.fr.general.data.TableDataException;
import com.fr.stable.StringUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工厂销售商品分析报表 -明细
 * @author liumingchun  17:45 2018-08-20
 */
public class FactorySalesDetailsReport extends AbstractTableData {
    /**
     * 字段名枚举YEAR
     */
    enum FIELD_NAME {
        PARTY_ID, DATE, WEEK_DAY, SALES_AMOUNT, CUSTOMER_AMOUNT, QUANTITY, STORE_SIZE
    }

    /**
     * 列名数组，保存程序数据集所有列名
     */
    private String[] columNames;
    /**
     * 保存查询得到列值
     */
    private LinkedHashSet<LinkedHashMap<String, Object>> rowData;

    /**
     * 构造函数，定义表结构，该表有10个数据列，列名为column#0，column#1，。。。。。。column#9
     */
    public FactorySalesDetailsReport() {
        // 定义tableName参数
//        setDefaultParameters(new Parameter[]{new Parameter("tableName")});
        // 定义程序数据集列名
        this.parameters = new Parameter[]{new Parameter("bgnDate"), new Parameter("endDate"), new Parameter("productId"), new Parameter("partyId")};
        // 填充字段名
        columNames = new String[FactorySalesDetailsReport.FIELD_NAME.values().length];
        int i = 0;
        for (FactorySalesDetailsReport.FIELD_NAME fieldName : FactorySalesDetailsReport.FIELD_NAME.values()) {
            columNames[i] = fieldName.toString();
            i++;
        }
    }

    @Override
    public int getColumnCount() throws TableDataException {
        return columNames.length;
    }

    @Override
    public String getColumnName(int columnIndex) throws TableDataException {
        return columNames[columnIndex];
    }

    @Override
    public int getRowCount() throws TableDataException {
        queryData();
        return rowData.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        queryData();
        int tempRowIndex = 0;
        for (LinkedHashMap<String, Object> row : rowData) {
            if (tempRowIndex == rowIndex) {
                return row.get(columNames[columnIndex]);
            }
            tempRowIndex += 1;
        }
        return null;
    }
    /**
     *  获取数据库连接 driverName和 url 可以换成您需要的
     * @return
     */
    public static Connection getConnection() {

        String driverName = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@10.10.201.97:1521:crmngpsd";
        String username = "zyngprd";
        String password = "zyngprd";
        Connection con = null;
        try {
            Class.forName(driverName);
            con = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return con;
    }
    /**
     * 查询数据
     */
    public void queryData() {
        // 确保只被执行一次
        if (rowData != null) {
            return;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

//        // 保存得到的数据库表名
        String bgnDate = parameters[0].getValue().toString();
        String endDate = parameters[1].getValue().toString();
        String productId = parameters[2].getValue().toString();
        String partyId = parameters[3].getValue().toString();

//        String productId = "10001','10002','10003";
//        String bgnDate = "Fri Oct 12 00:00:00 CST 2018";
//        String endDate = "Thu Oct 18 00:00:00 CST 2018";
//        String productId = "10229','10231";
//        String partyId = "6100";

        System.out.println("bgnDate:" + bgnDate + "endDate:" + endDate + "productId:" + productId);
//        开始时间
        Date bgnDateTime = new Date(bgnDate);
//        结束时间
        Date endDateTime = new Date(endDate);
        Calendar beginCa = Calendar.getInstance();
        beginCa.setTime(bgnDateTime);
        String beginCaTime = dateFormat.format(beginCa.getTime());
        Calendar endCa = Calendar.getInstance();
        endCa.setTime(endDateTime);
        String endCaTime = dateFormat.format(endCa.getTime());

        StringBuffer conditionSql = new StringBuffer();
        if (StringUtils.isNotBlank(productId)) {
            conditionSql.append(" and V.PRODUCT_ID in('" + productId + "')");
        }
//        if (StringUtils.isNotBlank(partyId)) {
//            conditionSql.append(" and Z.EXTEND3  in('" + partyId + "')");
//        }

        long start = System.currentTimeMillis();
        // 保存得到的结果集
        rowData = new LinkedHashSet<LinkedHashMap<String, Object>>();
        // 下面开始建立数据库连接，按照刚才的SQL语句进行查询
        Connection conn =  getConnection();
        try {

            Statement stmt = conn.createStatement();
            //查询经销商Id
            List partyList = new ArrayList();
            String partyIdSql = "SELECT s.party_id FROM zdev_store_info s where s.EXTEND3 = '" + partyId + "' GROUP BY s.party_id ORDER BY  s.party_id";
            ResultSet partyIdReportRs = stmt.executeQuery(partyIdSql.toString());
            LinkedHashMap<String, Object> partyMap;
            while (partyIdReportRs.next()) {
                partyMap = new LinkedHashMap<String, Object>();
                partyMap.put("partyId", partyIdReportRs.getString(1));
                partyList.add(partyMap);
            }
            partyIdReportRs.close();

            List reportList = new ArrayList();
            for (int i = 0; i < partyList.size(); i++) {
                LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) partyList.get(i);
                String partyIdForQuery = String.valueOf(map.get("partyId"));
                //判断表是否存在
                String tableExist = "select count(1) from user_tables where table_name = 'ZDEV_PS_DTL" + partyIdForQuery + "_V2'";
                ResultSet tableExistResultSet = stmt.executeQuery(tableExist);
                String tableExistFlag = "";
                while (tableExistResultSet.next()) {
                    tableExistFlag = tableExistResultSet.getString(1);
                }
                if ("1".equals(tableExistFlag)) {
                    System.out.println(partyIdForQuery);
                    StringBuffer paymentReportSql = new StringBuffer();
                    paymentReportSql.append("SELECT temp1.PARTY_ID,temp1.store_size,temp3.sales_amount ,temp3.customer_amount ,temp3.quantity ,temp1.EXTEND2 , ");
                    paymentReportSql.append("  CASE  to_char(to_date(temp1.EXTEND2,'YYYYMMDD') -1,'d') WHEN '1' then '星期一' WHEN '2' THEN '星期二' WHEN '3' THEN '星期三' WHEN '4' THEN '星期四' WHEN '5' THEN '星期五' WHEN '6' THEN '星期六' WHEN '7' THEN '星期日' END week_day ");
                    paymentReportSql.append(" FROM ");
                    paymentReportSql.append(" (select T.PARTY_ID, COUNT(T.STORE_ID) STORE_SIZE ,t.EXTEND2 from (");
                    paymentReportSql.append(" SELECT z.extend3 PARTY_ID, V.STORE_ID,V.EXTEND2 FROM ZDEV_PS_DTL" + partyIdForQuery + "_V2 V");
                    paymentReportSql.append(" INNER JOIN ZDEV_STORE_INFO Z ON V.STORE_ID = Z.STORE_ID ");
                    paymentReportSql.append("  WHERE v.DIM_TYPE = '01' AND v.EXTEND2 >= '" + beginCaTime + "'  AND v.EXTEND2 <= '" + endCaTime + "' ").append(conditionSql);
                    paymentReportSql.append("  GROUP BY Z.EXTEND3 , V.STORE_ID ,V.EXTEND2)T GROUP BY T.PARTY_ID ,t.EXTEND2 ) temp1");
                    paymentReportSql.append("  INNER JOIN ");
                    paymentReportSql.append(" (SELECT T.PARTY_ID,  t.EXTEND2,SUM(sales_amount) sales_amount,SUM(customer_amount) customer_amount,SUM(quantity) quantity from (");
                    paymentReportSql.append(" SELECT  Z.EXTEND3 PARTY_ID, V.EXTEND2, v.sales_amount,v.QUANTITY1 customer_amount,v.EXTEND7 quantity FROM ZDEV_PS_DTL" + partyIdForQuery + "_V2 V");
                    paymentReportSql.append(" INNER JOIN ZDEV_STORE_INFO Z ON V.STORE_ID = Z.STORE_ID ");
                    paymentReportSql.append("  WHERE v.DIM_TYPE = '01' AND v.EXTEND2 >= '" + beginCaTime + "'  AND v.EXTEND2 <= '" + endCaTime + "' ").append(conditionSql);
                    paymentReportSql.append("  GROUP BY Z.EXTEND3 ,v.sales_amount,V.EXTEND2,v.QUANTITY1 ,v.EXTEND7  )T GROUP BY T.PARTY_ID ,t.EXTEND2 ) temp3 ON temp1.party_id = temp3.party_id AND temp1.EXTEND2= temp3.EXTEND2");
                    ResultSet hourReportRs = stmt.executeQuery(paymentReportSql.toString());
                    while (hourReportRs.next()) {
                        LinkedHashMap<String, Object> info = new LinkedHashMap<String, Object>();
                        String party_id = String.valueOf(hourReportRs.getString("PARTY_ID"));
                        if (!partyId.equals(party_id)) {
                            continue;
                        }
                        BigDecimal storeSize = hourReportRs.getBigDecimal("STORE_SIZE");
                        BigDecimal salesAmount = hourReportRs.getBigDecimal("SALES_AMOUNT");
                        BigDecimal customerAmount = hourReportRs.getBigDecimal("CUSTOMER_AMOUNT");
                        BigDecimal quantity = hourReportRs.getBigDecimal("QUANTITY");
                        String date = String.valueOf(hourReportRs.getString("EXTEND2"));
                        String weekDay = String.valueOf(hourReportRs.getString("WEEK_DAY"));
                        System.out.println(partyIdForQuery + "," + party_id + "," + storeSize + "," + date + "," + weekDay);
                        if (reportList.size() < 1) {
                            info.put("PARTY_ID", party_id);
                            info.put("STORE_SIZE", storeSize);
                            info.put("SALES_AMOUNT", salesAmount);
                            info.put("CUSTOMER_AMOUNT", customerAmount);
                            info.put("QUANTITY", quantity);
                            info.put("DATE", date);
                            info.put("WEEK_DAY", weekDay);
                            reportList.add(info);
                        } else {
                            //如果有日期、品牌相同的，合并
                            boolean flag = true;
                            for (int j = 0; j < reportList.size(); j++) {
                                LinkedHashMap<String, Object> reportMap = (LinkedHashMap<String, Object>) reportList.get(j);
                                if (party_id.equals(reportMap.get("PARTY_ID")) && date.equals(reportMap.get("DATE"))) {
                                    flag = false;
                                    reportMap.put("STORE_SIZE", storeSize.add((BigDecimal) reportMap.get("STORE_SIZE")));
                                    reportMap.put("SALES_AMOUNT", salesAmount.add((BigDecimal) reportMap.get("SALES_AMOUNT")));
                                    reportMap.put("CUSTOMER_AMOUNT", customerAmount.add((BigDecimal) reportMap.get("CUSTOMER_AMOUNT")));
                                    reportMap.put("QUANTITY", quantity.add((BigDecimal) reportMap.get("QUANTITY")));
                                    break;
                                }
                            }
                            //年月小时均不同，添加进集合中成为新的元素
                            if (flag) {
                                info.put("PARTY_ID", party_id);
                                info.put("STORE_SIZE", storeSize);
                                info.put("SALES_AMOUNT", salesAmount);
                                info.put("CUSTOMER_AMOUNT", customerAmount);
                                info.put("QUANTITY", quantity);
                                info.put("DATE", date);
                                info.put("WEEK_DAY", weekDay);
                                reportList.add(info);
                            }
                        }
                    }
                    hourReportRs.close();
                }
            }
//            PARTY_ID, DATE, SALES_AMOUNT, CUSTOMER_AMOUNT, QUANTITY, STORE_SIZE
            //按照枚举类放置数据
            for (int i = 0; i < reportList.size(); i++) {
                LinkedHashMap<String, Object> reportMap = (LinkedHashMap<String, Object>) reportList.get(i);
                LinkedHashMap<String, Object> row = new LinkedHashMap<String, Object>();
                row.put(FIELD_NAME.PARTY_ID.toString(), reportMap.get(FIELD_NAME.PARTY_ID.toString()));
                row.put(FIELD_NAME.DATE.toString(), reportMap.get(FIELD_NAME.DATE.toString()));
                row.put(FIELD_NAME.WEEK_DAY.toString(), reportMap.get(FIELD_NAME.WEEK_DAY.toString()));
                row.put(FIELD_NAME.SALES_AMOUNT.toString(), reportMap.get(FIELD_NAME.SALES_AMOUNT.toString()));
                row.put(FIELD_NAME.CUSTOMER_AMOUNT.toString(), reportMap.get(FIELD_NAME.CUSTOMER_AMOUNT.toString()));
                row.put(FIELD_NAME.QUANTITY.toString(), reportMap.get(FIELD_NAME.QUANTITY.toString()));
                row.put(FIELD_NAME.STORE_SIZE.toString(), reportMap.get(FIELD_NAME.STORE_SIZE.toString()));
                rowData.add(row);
            }
            long end = System.currentTimeMillis();
            System.out.println("耗时：" + String.valueOf((end - start) / 1000) + "s");
            System.out.println(rowData.toString());
            // 释放数据库资源
            stmt.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 释放一些资源，因为可能会有重复调用，所以需释放valueList，将上次查询的结果释放掉
    @Override
    public void release() throws Exception {
        super.release();
        this.rowData = null;
    }
}
